﻿using Microsoft.Extensions.FileProviders;
using System;
using System.IO;

namespace IndexedFilePackageLibrary.FileProvider
{
    class PackageFileInfo : IFileInfo
    {
        private readonly string _path;
        private readonly FileInPackage _location;
        private readonly IndexedFilePackage.FileIndexNode _index;
        private readonly IndexedFilePackage.FileInfo _info; // =null means file not exists

        public PackageFileInfo(string path, FileInPackage location)
        {
            _path = path;
            _location = location;
            if (location.PackagePath != null && location.FileName != null)
            {
                try
                {
                    using (var package = IndexedFilePackage.Open(location.PackagePath))
                    {
                        _index = package.FindFile(location.FileName);
                        if (_index != null)
                        {
                            _info = package.GetFileInfo(_index);
                        }
                    }
                }
                catch (IOException)
                {
                    // File not found.
                }
            }
        }

        public bool Exists => _index != null;

        public long Length => _info?.FileSize ?? 0;

        public string PhysicalPath => null;

        public string Name => Path.GetFileName(_path);

        public DateTimeOffset LastModified
        {
            get
            {
                if (_info.LastModifiedTimeUtc == null)
                {
                    return DateTime.MinValue;
                }
                return _info.LastModifiedTimeUtc.Value;
            }
        }

        public bool IsDirectory => false;

        public Stream CreateReadStream()
        {
            var package = IndexedFilePackage.Open(_location.PackagePath, useAsyncStream: true);
            return package.SwitchToFileStream(_index.DangerousSkipParentValidation(), disposeParent: true);
        }
    }
}
